<template>
  <div class="filter-group-list">
    <div style="margin-bottom: 18px;display:flex;align-items:center;">
      <Title title="设置数据筛选" />
      <div class="filter-group-add" @click="addGroup"><i class="el-icon-plus"/> 添加筛选组</div>
    </div>
    <slot/>
    <div class="form-item">
      <div class="form-tiitle">数据筛选</div>
      <div v-if="computedFilterGroup && computedFilterGroup.length" style="flex:1;">
        <draggable
          v-model="computedFilterGroup"
          :disabled="!isDraggable"
          v-bind="dragOptions"
          handle=".draggable-move">
          <transition-group type="transition" >
            <div v-for="(item,index) in filterGroup" :key="item._id || index" class="filter-group-item">
              <div class="filter-group-name">
                <img :src="filterGroupIcon" class="icon" alt="">
                <div style="flex:1;"><el-input v-model="item.filterName" :maxlength="10" size="small" type="text" /></div>
                <div v-if="isDraggable" class="draggable-move">
                  <img :src="draggableImg" alt="" >
                </div>
                <div class="copy-group" title="复制" @click="copyGroup(item)"><img :src="copyGroupIcon" alt=""></div>
                <div class="delete-group" title="删除" @click="deleteGroup(index)"><img :src="deleteGroupIcon" alt=""></div>
              </div>
              <div class="filter-group-select">
                <FilterSelectModule
                  v-model="item.system"
                  :math-options="mathOptions"
                  :field-chidren-list="fieldChidrenList"
                  :unit-params="{
                    field: 'sourceName',
                  }"
                  key-name="uniqueId"
                  @changeData="changeData"
                  @syncGroup="syncGroup($event, index)"
                />
              </div>
            </div>
          </transition-group>
        </draggable>
      </div>
      <div v-else class="empty-text">请添加筛选组</div>
    </div>
  </div>
</template>

<script>
/**
 * 筛选组
*/
import DataFilter from '@/components/ReportManage/dataFilter/index';
import FilterSelectModule from '@/components/ReportManage/filterSelectModule';
import filterGroupIcon from '@/assets/reportManage/filter-group-icon.png';
import deleteGroupIcon from '@/assets/reportManage/delete-group.png';
import copyGroupIcon from '@/assets/reportManage/copy-group.png';
import Title from '@/components/Title';
import draggable from 'vuedraggable';
import draggableImg from '@/assets/chartsTheme/move.png';

export default {
  naem: 'FilterGroup',
  components: { DataFilter, FilterSelectModule, Title, draggable },
  model: {
    prop: 'filterGroup',
    event: 'changeData'
  },
  props: {
    filterGroup: { // 筛选组
      type: Array,
      default: () => {
        return [];
      }
    },
    fieldChidrenList: { // 可选择的字段
      type: Array,
      default: () => {
        return [];
      }
    },
    mathOptions: { // 算术选项
      type: Array,
      default: () => {
        return [];
      }
    },
    hasDataSource: { // 是否作为数据源
      type: Boolean,
      default: false
    },
    isDraggable: { // 是否可以拖拽
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      filterGroupIcon, deleteGroupIcon, copyGroupIcon, draggableImg,
      dragOptions: {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost'
      }
    };
  },
  computed: {
    computedFilterGroup: {
      get() {
        return this.filterGroup;
      },
      set(val) {
        this.$emit('changeData', val);
      }
    }
  },
  methods: {
    /** 操作事件 */
    // 添加组
    addGroup() {
      if (this.hasDataSource && this.filterGroup.length > 0) {
        this.$message.error('作为数据源仅能设置一组筛选组');
        return;
      }
      const name = `筛选组${this.filterGroup.length + 1}`;
      const group = {
        filterName: name,
        system: []
      };

      // 添加组的时候根据组的第一条数据进行同步
      if (this.filterGroup.length && this.filterGroup[0].system && this.filterGroup[0].system.length) {
        const fileteList = JSON.parse(JSON.stringify(this.filterGroup[0].system));
        fileteList.forEach(i => {
          const initData = {
            _id: new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999),
            top: i.top,
            field: i.field,
            isOpenFilter: i.isOpenFilter, // 是否开启筛选
            type: 0, // 0:时间筛选 1:条件筛选 2:文本筛选
            begin: '',
            end: '',
            optionsType: '',
            monthOnMonth: false,
            yearOnYear: false,
            operation: '', // 操作，=,>,<,>=,<= 和 包含，不包含，首字
            value: '',
            conditionValue: '',
            timeRangeType: '',
            reportField: '', // 【v2.8.9】报表字段（手动输入）,当选择的字段为报表字段时才生效
            defaultMath: i.defaultMath, // 默认筛选的运算条件
            defaultValue: '', // 默认筛选条件
            defaultNumberRange: [], // 默认筛选条件
            defaultTimeRange: [] // 默认筛选条件
          };
          if (this.isTimeField(i)) {
            initData.operation = i.operation;
            initData.optionsType = i.optionsType;
          }
          group.system.push(initData);
        });
      }
      this.filterGroup.push(group);
      this.changeData();
    },
    isTimeField(item) {
      // 字段的字段类型 optionsType  0:文本型 1:  时间日期  2: 数值型   3: 部门
      const optionsType = item.optionsType;
      // 如果 optionsType 存在则使用新逻辑，不存在则使用旧逻辑
      if (optionsType || optionsType === 0) {
        return optionsType === 1;
      }
      return item.field.indexOf('日期') >= 0 || item.field.indexOf('时间') >= 0 || item.field === '预计到款';
    },
    copyGroup(group) {
      if (this.hasDataSource && this.filterGroup.length > 0) {
        this.$message.error('作为数据源仅能设置一组筛选组');
        return;
      }
      const copyGroup = _.cloneDeep(group);
      copyGroup._id = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      copyGroup.filterName = `${copyGroup.filterName}-复制`;
      this.filterGroup.push(copyGroup);
      this.changeData();
    },
    // 删除组
    deleteGroup(index) {
      this.filterGroup.splice(index, 1);
      this.changeData();
    },
    syncGroup({ systemIndex, filterItem, deleteIndex = -1, syncField = [] }, groupIndex) {
      // 作用：所有筛选组需要保持一致
      const filterItemCopy = JSON.parse(JSON.stringify(filterItem || {}));
      if (this.filterGroup.length > 1) {
        this.filterGroup.forEach((i, index) => {
          if (index !== groupIndex && syncField.length === 0) {
            if (systemIndex >= 0) {
              // 修改字段
              this.$set(i.system, systemIndex, JSON.parse(JSON.stringify(filterItemCopy)));
            } else if (deleteIndex >= 0) {
              // 删除
              i.system.splice(deleteIndex, 1);
            }
          } else if (index !== groupIndex && syncField.length > 0) {
            // 部分字段
            syncField.forEach(j => {
              this.$set(i.system[systemIndex], j, filterItemCopy[j]);
            });
          }
        });
      }
    },
    changeData() {
      this.$emit('changeData', this.filterGroup);
    }
  }
};
</script>

<style lang="scss" scoped>
.filter-group-item {
  margin-bottom: 24px;
  &:last-child {
    margin-bottom: 0;
  }
  .filter-group-name {
    width: 100%;
    height: 40px;
    background: #f9f9f9;
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 8px;
    .icon {
      width: 16px;
      margin-right: 8px;
    }
    .delete-group {
      bottom: 0;
      font-size: 14px;
      cursor: pointer;
      i { font-size: 15px;}
      img {
        width: 12px;
      }
    }
    .copy-group {
      margin-right: 20px;
      cursor: pointer;
      img {
        width: 14px;
      }
    }
    &::v-deep {
      .el-input {
        width: 160px;
        display: flex;
        .el-input__inner {
          width: 100%;
          font-size: 14px;
          height: 28px;
        }
      }
    }
  }
}
.empty-text {
  font-size: 14px;
  color: #999;
  line-height: 32px;
}
.form-item {
  display: flex;
  .form-tiitle {
    font-size: 14px;
    text-align: right;
    color: #666;
    margin-right: 10px;
    width: 100px;
    line-height: 32px;
  }
}

.filter-group-add {
  cursor: pointer;
  display: inline-block;
  color: #406EFF;
  font-weight: 500;
  font-size: 14px;
}
.filter-group-select {
  position: relative;
  margin-left: 32px;
  &::before {
    position: absolute;
    left: -16px;
    content: '';
    height: 100%;
    width: 2px;
    background-color: #dde1ea;
    border-radius: 2px;
  }
}
.draggable-move {
  margin-right: 20px;
  cursor: move;
  img {
    width: 14px;
  }
}
</style>
